package com.ruoyi.hr.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.hr.common.annotation.HrLog;
import com.ruoyi.hr.common.constant.StatusConst;
import com.ruoyi.hr.common.utils.BaseThreadLocal;
import com.ruoyi.hr.common.utils.StatusParser;
import com.ruoyi.hr.domain.HrBgfile;
import com.ruoyi.hr.domain.HrCheck;
import com.ruoyi.hr.domain.dto.HrLogAddDto;
import com.ruoyi.hr.domain.vo.*;
import com.ruoyi.hr.service.IHrBgfileService;
import com.ruoyi.hr.service.IHrCheckService;
import com.ruoyi.hr.service.IHrOperateLogService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hr.domain.HrResume;
import com.ruoyi.hr.service.IHrResumeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * HR简历Controller
 * 
 * @author ruoyi
 * @date 2024-07-05
 */
@RestController
@RequestMapping("/hr/resume")
public class HrResumeController extends BaseController
{
    @Autowired
    private IHrResumeService hrResumeService;

    @Autowired
    private IHrCheckService hrCheckService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IHrOperateLogService logService;

    @Autowired
    private IHrBgfileService bgfileService;

    @Autowired
    private ServerConfig serverConfig;


    /**
     * 查询HR简历列表
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:list')")
    @GetMapping("/list")
    public TableDataInfo list(HrResumeQueryVo hrResume)
    {
        startPage();
        List<HrResume> list = hrResumeService.selectHrResumeListByType(hrResume);
        // 先查询出所有用户并封装为map
        Map<Long,String> userMap = new HashMap<>();
        List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
        sysUsers.stream().collect(Collectors.groupingBy(SysUser::getUserId)).forEach((key, value) -> userMap.put(key, value.get(0).getUserName()));
        // 返回数据调整
        List<HrResumeListVo> collect = list.stream().map(item -> {
            HrResumeListVo hrResumeListVo = new HrResumeListVo();
            BeanUtils.copyProperties(item, hrResumeListVo);
            // 查询背调资料
            HrBgfile hrBgfile = bgfileService.selectHrBgfileByResumeId(item.getId());

            if(hrBgfile != null){
                if (hrBgfile.getBgUrl().startsWith("http")){
                    // 是阿里云oss 的,直接设置
                    hrResumeListVo.setBgFile(hrBgfile.getBgUrl());
                }else {
                    // 背调文件下载地址
                    String path = "http://localhost:8090" + "/hr/bgfile/download/" + item.getId();
                    // 默认其是若依默认的一个文件上传到本地的路径, 需要换成本地的一个接口
                    hrResumeListVo.setBgFile(path);
                }
            }
            // 同时, 简历的地址也要修改一下
            if (!item.getResumeUrl().startsWith("http")) {
                hrResumeListVo.setResumeUrl("http://localhost:8090" + "/hr/resumefile/download/" + item.getId());
            }

            // 设置状态
            // 查询当前简历的检查状态
            HrCheck hrCheck = new HrCheck();
            hrCheck.setResumeId(item.getId());
            List<HrCheck> hrChecks = hrCheckService.selectHrCheckList(hrCheck);
            // 两个审核相关的list
            List<String> resumeCheckList = new ArrayList<>();
            List<String> hireCheckList = new ArrayList<>();
            StatusParser statusParser = new StatusParser(item.getStatus());
            hrChecks.forEach(checker -> {
                if (userMap.containsKey(checker.getUid())) {
                    String userName = userMap.get(checker.getUid()) + StatusConst.Check.CheckStatus.getMsgByCode(Math.toIntExact(checker.getIsCheck()));
                    if (checker.getType() == StatusConst.Check.TypeStatus.Resume.getCode()) {
                        // 简历审核
                        resumeCheckList.add(userName);
                    } else {
                        // 录用审核
                        hireCheckList.add(userName);
                    }
                }
            });
            if(resumeCheckList.size() == 0){
                resumeCheckList.add("未审核");
            }
            if(hireCheckList.size() == 0){
                hireCheckList.add("未审核");
            }

            hrResumeListVo.setBgCheck(statusParser.getBgStatusName());
            hrResumeListVo.setResumeCheck(resumeCheckList);
            hrResumeListVo.setHireCheck(hireCheckList);
            // 设置简历状态
            hrResumeListVo.setStatusStr(statusParser.getResumeStatusName());

            return hrResumeListVo;
        }).collect(Collectors.toList());
        return getDataTable(collect);
    }

    /**
     * 导出HR简历列表
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:export')")
    @Log(title = "HR简历", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HrResume hrResume)
    {
        List<HrResume> list = hrResumeService.selectHrResumeList(hrResume);
        ExcelUtil<HrResume> util = new ExcelUtil<HrResume>(HrResume.class);
        util.exportExcel(response, list, "HR简历数据");
    }

    /**
     * 获取HR简历详细信息
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        HrResume hrResume = hrResumeService.selectHrResumeById(id);
        HrResumeQueryVo hrResumeQueryVo = new HrResumeQueryVo();
        BeanUtils.copyProperties(hrResume,hrResumeQueryVo);
        // 从审核表中查询当前简历对应的审核人
        // 先查询出所有用户并封装为map
        Map<Long,String> userMap = new HashMap<>();
        List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
        sysUsers.stream().collect(Collectors.groupingBy(SysUser::getUserId)).entrySet().forEach(item->{
            userMap.put(item.getKey(),item.getValue().get(0).getUserName());
        });

        HrCheck hrCheck = new HrCheck();
//        hrCheck.setIsCheck(0);
        hrCheck.setType(1);
        hrCheck.setResumeId(id);
        List<HrCheck> hrChecks = hrCheckService.selectHrCheckList(hrCheck);
        List<String> userName = hrChecks.stream().map(item -> {
            return userMap.get(item.getUid());
        }).collect(Collectors.toList());
        hrResumeQueryVo.setRuserNames(userName);
        List<Long> ruserIds = hrChecks.stream().map(HrCheck::getUid).collect(Collectors.toList());
        hrResumeQueryVo.setRuserIds(ruserIds);
        hrResumeQueryVo.setRuserNames(userName);
        return success(hrResumeQueryVo);
    }

    /**
     * 新增HR简历
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:add')")
    @Log(title = "HR简历", businessType = BusinessType.INSERT)
    @HrLog(operationType = "添加简历")
    @PostMapping
    public AjaxResult add(@RequestBody HrResumeAddVo hrResume)
    {


        return toAjax(hrResumeService.insertHrResume(hrResume));
    }

    /**
     * 修改HR简历
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @Log(title = "HR简历", businessType = BusinessType.UPDATE)
    @HrLog(operationType = "简历修改")
    @PutMapping
    public AjaxResult edit(@RequestBody HrResumeAddVo hrResume)
    {
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        List<Long> list = new ArrayList<>();
        list.add(hrResume.getId());
        hrLog.setResumeIds(list);
        hrLog.setContent("简历修改");
        hrResumeService.updateHrResumeWithCheck(hrResume);
        return AjaxResult.success();
    }

    /**
     * 删除HR简历
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:remove')")
    @Log(title = "HR简历", businessType = BusinessType.DELETE)
    @HrLog(operationType = "简历删除")
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("删除简历");
        return toAjax(hrResumeService.deleteHrResumeByIds(ids));
    }


    /**
     * 添加无效库
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "简历转入无效库")
    @PutMapping("/addFailure/{ids}")
    public AjaxResult addFailure(@PathVariable Long[] ids)
    {
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("将简历添加到无效库, 投递的简历有问题");
        return toAjax(hrResumeService.updatePositionBatch(ids, StatusConst.Resume.PositionStatus.FAILURE.getCode()));
    }

    /**
     * 添加黑名单
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "简历转入黑名单")
    @PutMapping("/addBlack/{ids}")
    public AjaxResult addBlack(@PathVariable Long[] ids)
    {
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("将简历添加到黑名单");

        return toAjax(hrResumeService.updatePositionBatch(ids, StatusConst.Resume.PositionStatus.BLACK.getCode()));
    }

    /**
     * 添加人才库
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "简历转入人才库")
    @PutMapping("/addAbility/{ids}")
    public AjaxResult addAbility(@PathVariable Long[] ids)
    {
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("将简历添加到人员库备用");

        return toAjax(hrResumeService.updatePositionBatch(ids, StatusConst.Resume.PositionStatus.TALENT.getCode()));
    }

    /**
     * 简历审核
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "审核")
    @PutMapping("/doCheck")
    public AjaxResult doCheck(@RequestBody HrCheckVo hrCheckVo){
        // TODO 审核只有当前是这个简历的审核人才能审核捏
        // 查询当前简历的所有审核人, 看看当前操作人是否在这里面, 不在这里面则不让审核呗
        Boolean flag = hrCheckService.ifCanCheck(hrCheckVo.getResumeIds(),hrCheckVo.getCheckType());
        if (!flag){
            HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
            hrLog.setResumeIds(new ArrayList<>());
            return AjaxResult.error("当前审核人并没有被分配到某个简历, 或者是已经审核过了, 请重新选择");
        }
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(hrCheckVo.getResumeIds());
        hrLog.setAdvice(hrCheckVo.getAdvice());
        if (hrCheckVo.getCheckType() == StatusConst.Check.TypeStatus.Resume.getCode()){
            // 简历审核
            if (hrCheckVo.getStatus() == StatusConst.Check.CheckStatus.PASS.getCode()){
                // 审核通过
                hrLog.setContent("简历审核通过");
            }else {
                // 驳回
                hrLog.setContent("简历不通过, 简历被驳回");

            }
        }else {
            // 录用审核
            if (hrCheckVo.getStatus() == StatusConst.Check.CheckStatus.PASS.getCode()){
                hrLog.setContent("录用审核通过");
            }else {
                hrLog.setContent("录用不通过, 被驳回");
            }
        }


        hrResumeService.updateHrCheckBatch(hrCheckVo);
        return AjaxResult.success("审核成功");
    }


    /**
     * 录用审核分配
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "录用审核分配")
    @PostMapping("/dispatch")
    public AjaxResult doDispatch(@RequestBody HrCheckDispatchVo dispatchVo){
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(dispatchVo.getResumeIds());
        hrLog.setContent("进行录用审核的人员分配");
        hrCheckService.insertBatchWithUserIds(dispatchVo);
        return AjaxResult.success();
    }

    /**
     * 入职
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "入职")
    @PostMapping("/doInduction/{ids}")
    public AjaxResult doInduction(@PathVariable Long[] ids){
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("人员入职操作");

        hrResumeService.doInduction(ids,1);
        return AjaxResult.success();
    }

    /**
     * 取消入职
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "入职取消")
    @PostMapping("/cancelInduction/{ids}")
    public AjaxResult cancelInduction(@PathVariable Long[] ids){
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("取消人员入职");
        hrResumeService.doInduction(ids,2);
        return AjaxResult.success();
    }


    /**
     * 点击发送offer
     */
    @PreAuthorize("@ss.hasPermi('hr:resume:edit')")
    @HrLog(operationType = "offer发送")
    @PostMapping("/sendOffer/{ids}")
    public AjaxResult sendOffer(@PathVariable Long[] ids){
        HrLogAddDto hrLog = BaseThreadLocal.getHrLog();
        hrLog.setResumeIds(List.of(ids));
        hrLog.setContent("进行offer的发送");
        hrResumeService.sendOffer(ids);
        return AjaxResult.success();
    }

    /**
     * 是否接受offer
     */
    @PostMapping("/isOk/{flag}")
    public AjaxResult isOk(@PathVariable("flag") Integer flag){
        if (flag == 0){
            return AjaxResult.success("不接受");
        }else {
            return AjaxResult.success("接受");
        }
    }

}
